# -*- coding:utf-8 -*-

"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: 2023/5/29:15:54
@product: PyCharm
=============================
"""

from PyQt5.QtWidgets import QDialog

from gtyTools import gtyTypes
from gtyUI import uiTools
from uiFiles import ui_settings
from gtyConfig import language
import gtyTools.tools
import subprocess, re

class Settings(QDialog, ui_settings.Ui_SettingsDialog):
    def __init__(self, mainPage, eventQ, parent=None):
        super(Settings, self).__init__(parent)
        self.setupUi(self)

        uiTools.centerAndSetIcon(self)
        self.setGeometry(-200, -200, self.width(), self.height())

        self.mainPage = mainPage
        self.eventQ = eventQ
        # 获取配置文件
        self.configHandlers = gtyTypes.ConfigHandlers()

        self.beepEnable = self.configHandlers.machine.read('machine', 'beepEnable') != '0'
        self.BeepChB.setChecked(self.beepEnable)
        self.BeepChB.stateChanged.connect(self.toggleBeep)

        self.newFileBtn.clicked.connect(self.createNewFile)
        self.mainPage.eventEngine.eventList["ui_recordFileUrl"].connect(self.updateNewFileDisplay)

        self.backButton.setText(language.settings_back)
        self.label3.setText(language.settings_beeper)
        self.label4.setText(language.settings_newRecordFile)
        self.newFileBtn.setText(language.settings_create)
        self.passiveRBtn.setText(language.settings_passive)
        self.activeRBtn.setText(language.settings_active)

        self.passiveRBtn.clicked.connect(self.setPassive)
        self.activeRBtn.clicked.connect(self.setActive)

        self.lineEdit.setText('')
        self.timeZone = 0
        self.SetBtn.clicked.connect(lambda: self.setTimeZone('set'))
        self.plusButton.clicked.connect(lambda: self.setTimeZone('+'))
        self.minusButton.clicked.connect(lambda: self.setTimeZone('-'))

        #通过读取配置文件来保存有源无源的状态
        if self.configHandlers.machine.read('machine', 'hardwareType') == 'F2000':
            if self.configHandlers.machine.read('machine', 'machineState') == 'Active':
                self.activeRBtn.setChecked(True)
            else:
                self.passiveRBtn.setChecked(True)
        else:
            self.passiveRBtn.hide()
            self.activeRBtn.hide()
        self.time_zone_mapping = {
            '0:00': "Etc/UTC",  # UTC
            '+1:00': "Europe/London",  # UTC+1 (Central European Time)
            '+2:00': "Africa/Johannesburg",  # UTC+2 (South Africa Standard Time)
            '+3:00': "Asia/Riyadh",  # UTC+3 (Arabian Standard Time)
            '+3:30': "Asia/Tehran",  # UTC+3:30 (Iran Standard Time)
            '+4:00': "Asia/Dubai",  # UTC+4 (Gulf Standard Time)
            '+4:30': "Asia/Kabul",  # UTC+4:30 (Afghanistan Time)
            '+5:00': "Asia/Karachi",  # UTC+5 (Pakistan Standard Time)
            '+5:30': "Asia/Kolkata",  # UTC+5:30 (Indian Standard Time)
            '+5:45': "Asia/Kathmandu",  # UTC+5:45 (Nepal Time)
            '+6:00': "Asia/Kashgar",  # UTC+6 (Bangladesh Standard Time)
            '+6:30': "Asia/Yangon",  # UTC+6:30 (Myanmar Time)
            '+7:00': "Asia/Bangkok",  # UTC+7 (Indochina Time)
            '+8:00': "Asia/Shanghai",  # UTC+8 (China Standard Time)
            '+8:45': "Australia/Eucla",  # UTC+8:45 (Central Western Standard Time)
            '+9:00': "Asia/Tokyo",  # UTC+9 (Japan Standard Time)
            '+9:30': "Australia/Darwin",  # UTC+9:30 (Central Standard Time, Australia)
            '+10:00': "Australia/Queensland",  # UTC+10 (Australian Eastern Standard Time)
            '+10:30': "Australia/South",  # UTC+10:30 (Lord Howe Island Time)
            '+11:00': "Australia/Sydney",  # UTC+11 (New Caledonia Time)
            '+12:00': "Pacific/Fiji",  # UTC+12 (Fiji Time)
            '+13:00': "Pacific/Tongatapu",  # UTC+13 (Tonga Time)
            '+13:45': "Pacific/Chatham",  # UTC+13:45 (Tonga Summer Time)
            '+14:00': "Pacific/Kiritimati",  # UTC+14 (Line Islands Time)
            '-1:00': "Atlantic/Azores",  # UTC-1 (Azores Time)
            '-2:00': "Atlantic/South_Georgia",  # UTC-2 (Cape Verde Time)
            '-2:30': "America/St_Johns",  # UTC-2:30 (Newfoundland Time)
            '-3:00': "America/Argentina/Buenos_Aires",  # UTC-3 (Argentina Time)
            '-4:00': "America/New_York",  # UTC-4 (Eastern Standard Time)
            '-5:00': "America/Winnipeg",  # UTC-5 (Eastern Standard Time, US/Canada)
            '-6:00': "America/Costa_Rica",  # UTC-6 (Central Standard Time)
            '-7:00': "America/Creston",  # UTC-7 (Mountain Standard Time)
            '-8:00': "America/Juneau",  # UTC-8 (Pacific Standard Time)
            '-9:00': "Pacific/Gambier",  # UTC-9 (Hawaii-Aleutian Standard Time)
            '-9:30': "Pacific/Marquesas",  # UTC-9:30 (Marquesas Islands Time)
            '-10:00': "Pacific/Tahiti",  # UTC-10 (Tahiti Time)
            '-11:00': "Pacific/Midway",  # UTC-11 (Midway Islands Time)
            '-12:00': "Etc/GMT-12"  # UTC-12 (GMT-12 Time Zone)
        }

        self.get_current_timezone()
    def sendEvent(self, task, eventName, eventData=None):
        if eventData is None:
            eventData = []
        e = [eventName, eventData]
        try:
            if task.upper() in self.eventQ.keys():
                self.eventQ[task.upper()].put(e)
        except Exception as e:
            print(e)

    def toggleBeep(self):
        self.beepEnable = not self.beepEnable
        value = '1' if self.beepEnable else '0'
        self.configHandlers.machine.write('machine', 'beepEnable', value)
        self.BeepChB.setChecked(self.beepEnable)
        self.sendEvent('UART', 'uart_beepEnable', [int(self.beepEnable)])
        if self.beepEnable:
            self.sendEvent('UART', 'uart_beep', 0.5)

    def createNewFile(self):
        self.sendEvent('IO', 'file_loadEventConfigFile', [True])
        self.label_info.setText('New record file created')

    def updateNewFileDisplay(self, data):
        print(__file__, data)
        self.label_info.setText('New record file: ' + data[0])

    def setPassive(self):
        self.sendEvent('UART', 'uart_setPassive')
        self.sendEvent('UI','ui_setPassOrAct','Passive')
        self.configHandlers.machine.write('machine', 'machineState', 'Passive')

    def setActive(self):
        self.sendEvent('UART', 'uart_setActive')
        self.sendEvent('UI', 'ui_setPassOrAct','Active')
        self.configHandlers.machine.write('machine', 'machineState', 'Active')

    def setTimeZone(self, data):
        # 获取时区列表，按时区顺序排序
        mapping = self.time_zone_mapping
        sorted_time_zones = sorted(mapping.keys(), key=lambda x: (int(x.split(':')[0]), int(x.split(':')[1])))
        if data == '+':
            # 获取当前时区的索引
            current_time_zone = self.lineEdit.text().strip()
            if current_time_zone not in sorted_time_zones:
                current_time_zone = '0:00'  # 默认到UTC时区
            current_index = sorted_time_zones.index(current_time_zone)
            # 获取下一个时区索引
            next_index = (current_index + 1) % len(sorted_time_zones)
            next_time_zone = sorted_time_zones[next_index]
            self.lineEdit.setText(next_time_zone)
            self.label_info.setText(mapping[next_time_zone])
        elif data == '-':
            # 获取当前时区的索引
            current_time_zone = self.lineEdit.text().strip()
            if current_time_zone not in sorted_time_zones:
                current_time_zone = '0:00'  # 默认到UTC时区
            current_index = sorted_time_zones.index(current_time_zone)
            # 获取上一个时区索引
            prev_index = (current_index - 1) % len(sorted_time_zones)
            prev_time_zone = sorted_time_zones[prev_index]
            self.lineEdit.setText(prev_time_zone)
            self.label_info.setText(mapping[prev_time_zone])

        if data == 'set':
            str1 = self.lineEdit.text()
            if str1 in mapping:
                setTimeZoneStr = 'timedatectl set-timezone '
                setTimeZoneStr += f" '{mapping[str1]}' "
                gtyTools.tools.linuxSudoCmd(setTimeZoneStr)
                gtyTools.tools.linuxSudoCmd('systemctl restart chrony.service')
                self.label_info.setText("set timezone success ")
            else:
                self.label_info.setText('cannot find timezone in mapping')
                self.label_info.setText('Please input correct formatting, like +5:30')

    def get_current_timezone(self):
        # 执行timedatectl status命令并获取输出
        result = subprocess.run(['timedatectl', 'status'], capture_output=True, text=True)
        # 匹配时区信息，时区信息的格式为 "Time zone: Asia/Kolkata (IST, +0530)"
        match = re.search(r"Time zone:\s+([\w/]+)", result.stdout)
        if match:
           for key, value in self.time_zone_mapping.items():
               if value == match.group(1):
                   self.lineEdit.setText(key)  # 设置到lineEdit中
                   self.label_info.setText(match.group(1))